/**
 * cookie相关
 * @param {*} vel
 */

const Cookie = function () {
    this.get = this.$get
    this.set = this.$set
    this.del = this.$del
}

Cookie.prototype.$set = function (key, value, delay) {
    //默认cookie为七天之后过期 3s 4m 5h 7d 秒 分 时 天
    if (delay == undefined) delay = "7d";

    delay = (delay || "7d").toLowerCase();

    var expireDate = new Date();

    var num = parseInt(delay);
    if (delay.indexOf("d") !== -1) {
        expireDate.setDate(expireDate.getDate() + num);
    } else if (delay.indexOf("h") !== -1) {
        expireDate.setHours(expireDate.getHours() + num);
    } else if (delay.indexOf("m") !== -1) {
        expireDate.setMinutes(expireDate.getMinutes() + num);
    } else if (delay.indexOf("s") !== -1) {
        expireDate.setSeconds(expireDate.getSeconds() + num);
    } else {
        expireDate.setDate(expireDate.getDate() + num);
    }
    if (typeof value == "object") {
        value = JSON.stringify(value);
    }

    value = encodeURIComponent(value);

    document.cookie =
        key + "=" + value + ";expires=" + expireDate.toGMTString();
    return this.get(key);
}
Cookie.prototype.$get = function (key) {
    var objCookie = {};
        var cookie = document.cookie;
        var keyValueList = cookie.split(";");
        for (var index in keyValueList) {
            var keyValue = keyValueList[index].split("=");
            var k = keyValue[0].trim();
            var v = keyValue[1];
            v = decodeURIComponent(v);
            v = this.decodeJson(v);
            objCookie[k] = v;
        }

        if (typeof key == "undefined") {
            return objCookie;
        }

        return objCookie[key];
}
Cookie.prototype.$del = function (key) {
    //删除所有cookie
    if (typeof key == "undefined") {
        var cookieList = this.get();
        for (key in cookieList) {
            this.del(key);
        }
        return true;
    } else {
        if (this.get(key) == "undefined") {
            return false;
        } else {
            return this.set(key, "", "0s");
        }
    }
}
Cookie.prototype.decodeJson = function (value) {
    //数组转成的对象字符串
    var regAryStr = /^\[[\s|\S]*\]$/;
    //对象转成的对象字符串
    var regObjStr = /^\{([\"\s|\S]+\"\:\"[\s|\S]*)+\"\}$/;
    if (regAryStr.test(value)) {
        return eval("(" + value + ")");
    }
    if (regObjStr.test(value)) {
        return JSON.parse(value);
    }
    return value;
}

module.exports =  new Cookie()